import React, { Component } from "react";
import { observer } from "mobx-react";
import { Icon } from "weaver-mobile";
import { MapPage } from "weaver-mobile-page";

const Normal = MapPage.Normal;
let map;

@observer
export default class Map extends Component {
    constructor(props){
        super(props);
    }

    mapEvents = {
        created: instance => this.setMapInstance(instance)
    };

    setMapInstance = instance => {
        if (instance.CLASS_NAME === "AMap.Map") {
            map = instance;
            this.initMarker();
        }
    }

    initMarker = () => {
        const {currentPositionData, positionStatus} = this.props.store;
        if(map != null && positionStatus){
            const position = [currentPositionData.longitude, currentPositionData.latitude];
            let overlays = map.getAllOverlays("marker");
            let marker;
            if(overlays.length == 0){
                marker = new window.AMap.Marker({
                    position: position,
                });
                map.add(marker);
            }else{
                marker = overlays[0];
                marker.setPosition(position);
            }
            try{
                setTimeout(() => map.setCenter(position), 20);    
            }catch(e){
                setTimeout(() => map.setCenter(position), 20);
            }
        }else{

        }
    }

    render() {
        const {positionStatus, initMapPage} = this.props.store;
        const mapProps = {
            showIntroduction: false,
            dragEnable: false,
            events: this.mapEvents,
            children: <div />
        }
        if(positionStatus){
            this.initMarker();
        }

        return (
            <Normal {...mapProps}>
                <div className='relocate' onClick={initMapPage}>
                    <Icon className='icon' type='positioning' color='#999' size='ms'/>
                </div>
            </Normal>
        );
    }
}